/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package frames;

import com.lowagie.text.Document;
import com.lowagie.text.PageSize;
import com.lowagie.text.pdf.DefaultFontMapper;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.rmi.AccessException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import reportesdeer.IReportes;
import reportesdeer.PropiedadesReportes;
import reportesdeer.Reportes;

/**
 *
 * @author Rossy
 */
public class Reporte4 extends javax.swing.JFrame {

    /**
     * Creates new form Reporte4
     */
    
    String port;
    String server;
    Properties reportesPropiedades;
    
    public Reporte4() {
        initComponents();
//        inicializar();    
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        cmbHoraInicial = new javax.swing.JComboBox();
        cmbHoraFinal = new javax.swing.JComboBox();
        btnGenerar = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        cmbDia = new javax.swing.JComboBox();
        btnGuardar = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        cmbHoraInicial.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23" }));

        cmbHoraFinal.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23" }));

        btnGenerar.setText("Generar");
        btnGenerar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGenerarActionPerformed(evt);
            }
        });

        jLabel2.setText("Dia:");

        cmbDia.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "lunes", "martes", "miercoles", "jueves", "viernes", "sabado", "domingo" }));

        btnGuardar.setText("Guardar");
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        jLabel3.setText("Rango de horas para el reporte:");

        jLabel4.setText("Desde");

        jLabel5.setText("horas");

        jLabel6.setText("Hasta");

        jLabel7.setText("horas");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btnGenerar)
                        .addGap(18, 18, 18)
                        .addComponent(btnGuardar))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel4)
                                .addGap(6, 6, 6)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(cmbHoraInicial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jLabel5)
                                        .addGap(43, 43, 43)
                                        .addComponent(jLabel6)
                                        .addGap(18, 18, 18)
                                        .addComponent(cmbHoraFinal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(6, 6, 6)
                                        .addComponent(jLabel7))
                                    .addComponent(cmbDia, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addComponent(jLabel2))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jLabel6)
                    .addComponent(jLabel5)
                    .addComponent(jLabel7)
                    .addComponent(cmbHoraInicial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cmbHoraFinal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(cmbDia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnGuardar)
                    .addComponent(btnGenerar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnGenerarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGenerarActionPerformed
        try {
            String strHoraInicial = this.cmbHoraInicial.getSelectedItem().toString();
            String strHoraFinal = this.cmbHoraFinal.getSelectedItem().toString();
            String strDia = this.cmbDia.getSelectedItem().toString();
            int arrayVehiculos[];
            int horaInicial = Integer.parseInt(strHoraInicial);
            int horaFinal = Integer.parseInt(strHoraFinal);

            if (horaInicial > horaFinal) {
                JOptionPane.showMessageDialog(null, "Por favor, ingrese los datos correctos", "REPORTES", JOptionPane.ERROR_MESSAGE);
            } else {
                if (horaFinal == 0) {
                    horaFinal = 23;
                }
                Reportes dao = new Reportes();
                arrayVehiculos = dao.generarReporte4(strDia, horaInicial, horaFinal);
                
//                Registry reg = LocateRegistry.getRegistry(port, 1099);
//                IReportes rmi = (IReportes)reg.lookup(server);
//                arrayVehiculos=rmi.generarReporte4(strDia,horaInicial,horaFinal);
                DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
                for (int i = horaInicial; i <= horaFinal; i++) {
                    //            System.out.println("hora ="+i+", valor="+arrayPatron[i]);
                    dataSet.setValue(arrayVehiculos[i], "" + arrayVehiculos[i], "" + i);
                }
                JFreeChart chart = ChartFactory.createBarChart("Nivel de carga vehicular por hora", "Horas", "Cantidad de Vehículos", dataSet, PlotOrientation.VERTICAL, true, true, true);
                CategoryPlot plot = chart.getCategoryPlot();
                plot.setRangeGridlinePaint(Color.BLACK);
                BarRenderer renderer = (BarRenderer) plot.getRenderer();
                renderer.setDrawBarOutline(false);
                GradientPaint gp0 = new GradientPaint(0.0f, 0.0f, Color.MAGENTA, 0.0f, 0.0f, new Color(0, 0, 64));
                renderer.setSeriesPaint(0, gp0);

                ChartFrame frame = new ChartFrame("Reporte 4", chart);
                frame.setVisible(true);
                frame.setSize(800, 500);
//                writeChartToPDF(chart, 800, 500, "Reporte4.pdf");
            }
        } catch (RemoteException ex) {
            Logger.getLogger(Reporte4.class.getName()).log(Level.SEVERE, null, ex);
        } 
    }//GEN-LAST:event_btnGenerarActionPerformed

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
      try {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setAcceptAllFileFilterUsed(false);
            FileNameExtensionFilter filter = new FileNameExtensionFilter("PDF files", "pdf");
            fileChooser.addChoosableFileFilter(filter);
            fileChooser.showSaveDialog(null);
            File file = fileChooser.getSelectedFile();
            String filename = file.getAbsolutePath();

            String strHoraInicial = this.cmbHoraInicial.getSelectedItem().toString();
            String strHoraFinal = this.cmbHoraFinal.getSelectedItem().toString();
            String strDia = this.cmbDia.getSelectedItem().toString();
            int arrayVehiculos[];
            int horaInicial = Integer.parseInt(strHoraInicial);
            int horaFinal = Integer.parseInt(strHoraFinal);

            if (horaInicial > horaFinal) {
                JOptionPane.showMessageDialog(null, "Por favor, ingrese los datos correctos", "REPORTES", JOptionPane.ERROR_MESSAGE);
            } else {
                    if (horaFinal == 0) horaFinal = 23;
                    
                    Reportes dao = new Reportes();
                    arrayVehiculos = dao.generarReporte4(strDia, horaInicial, horaFinal);
                    
//                    Registry reg = LocateRegistry.getRegistry(port, 1099);
//                    IReportes rmi = (IReportes)reg.lookup(server);
//                    arrayVehiculos=rmi.generarReporte4(strDia,horaInicial,horaFinal);
                
                    DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
                    for (int i = horaInicial; i <= horaFinal; i++) {
                        dataSet.setValue(arrayVehiculos[i], "" + arrayVehiculos[i], "" + i);
                    }
                    JFreeChart chart = ChartFactory.createBarChart("Reporte 4", "Horas", "Cantidad de Vehículos", dataSet, PlotOrientation.VERTICAL, true, true, true);
                    CategoryPlot plot = chart.getCategoryPlot();
                    plot.setRangeGridlinePaint(Color.BLACK);
                    BarRenderer renderer = (BarRenderer) plot.getRenderer();
                    renderer.setDrawBarOutline(false);
                    GradientPaint gp0 = new GradientPaint(0.0f, 0.0f, Color.MAGENTA, 0.0f, 0.0f, new Color(0, 0, 64));
                    renderer.setSeriesPaint(0, gp0);
                    writeChartToPDF(chart, 800, 500, filename);
                    this.dispose();

            }

        } catch (Exception e) {
        }

    }//GEN-LAST:event_btnGuardarActionPerformed

//    /**
//     * @param args the command line arguments
//     */
//    public static void main(String args[]) {
//        /* Set the Nimbus look and feel */
//        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
//        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
//         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
//         */
//        try {
//            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
//                if ("Nimbus".equals(info.getName())) {
//                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
//                    break;
//                }
//            }
//        } catch (ClassNotFoundException ex) {
//            java.util.logging.Logger.getLogger(Reporte4.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (InstantiationException ex) {
//            java.util.logging.Logger.getLogger(Reporte4.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (IllegalAccessException ex) {
//            java.util.logging.Logger.getLogger(Reporte4.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
//            java.util.logging.Logger.getLogger(Reporte4.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        }
//        //</editor-fold>
//
//        /* Create and display the form */
//        java.awt.EventQueue.invokeLater(new Runnable() {
//            public void run() {
//                new Reporte4().setVisible(true);
//            }
//        });
//    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnGenerar;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JComboBox cmbDia;
    private javax.swing.JComboBox cmbHoraFinal;
    private javax.swing.JComboBox cmbHoraInicial;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    // End of variables declaration//GEN-END:variables

    private void writeChartToPDF(JFreeChart chart, int width, int height, String fileName) {
        PdfWriter writer = null;
//        Document document = new Document();
        Document document = new Document(PageSize.LETTER.rotate());

        try {
            writer = PdfWriter.getInstance(document, new FileOutputStream(fileName+".pdf"));
            document.open();
            PdfContentByte contentByte = writer.getDirectContent();
            PdfTemplate template = contentByte.createTemplate(width, height);
            Graphics2D graphics2d = template.createGraphics(width, height, new DefaultFontMapper());
            Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, width, height);
            chart.draw(graphics2d, rectangle2d);
            graphics2d.dispose();
            contentByte.addTemplate(template, 0, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        document.close();
    }

//    private void inicializar() {
//        this.reportesPropiedades = new PropiedadesReportes().getProperties();
//        port = this.reportesPropiedades.getProperty("port");
//        server = this.reportesPropiedades.getProperty("server");
//    }

}
